package leet_code;

import java.awt.event.WindowFocusListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 二叉树相关
 */
public class A_8_BinaryTree {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 中序遍历二叉树
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        insertNumber(res, root);
        return res;
    }

    private void insertNumber(List<Integer> list, TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            insertNumber(list, root.left);
        }
        list.add(root.val);
        if (root.right != null) {
            insertNumber(list, root.right);
        }
    }

    /**
     * 二叉树的最大深度
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int count = 0;
        return countDepth(count, root);
    }
    private int countDepth(int count, TreeNode root) {
        count++;
        int leftCount = root.left == null? count : countDepth(count, root.left);
        int rightCount = root.right == null? count : countDepth(count, root.right);
        return Math.max(leftCount, rightCount);
    }

    public TreeNode invertTree(TreeNode root) {
        //从底反转到顶
        if (root == null) {
            return null;
        }
        if (root.right == null && root.left ==null) {
            return root;
        }
        TreeNode l = invertTree(root.left);
        TreeNode r = invertTree(root.right);

        root.left = r;
        root.right = l;
        return root;
    }
}
